package fan

import (
	"blog/models"
	"crypto/md5"
	"fmt"
	"html/template"
	"net/http"
	"strconv"
	"strings"

	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
)

type DefaultController struct {
	BaseController
}

func (con DefaultController) Index(c *gin.Context) {
	username := con.getName(c)
	cats := models.Selects("SELECT *  FROM fa_cat")
	sql := "select id,title,clicks,cat,cat1,cat2,top,hot,post_time ,(select cname from fa_cat where id = cat) as catname,(select cname from fa_cat where id = cat1) as cat1name,(select cname from fa_cat where id = cat2) as cat2name from fa_article   limit 10 "
	lists := models.Selects(sql)

	sql1 := "select id,title,post_time from fa_article   order by hot desc limit 10"
	list1 := models.Selects(sql1)

	sql2 := "select id,title,post_time from fa_article   order by clicks desc limit  10"
	list2 := models.Selects(sql2)

	c.HTML(http.StatusOK, "default/index.html", gin.H{
		"username": username,
		"cats":     cats,
		"list":     lists,
		"list1":    list1,
		"list2":    list2,
	})
}

func (con DefaultController) Login(c *gin.Context) {
	username := con.getName(c)
	c.HTML(http.StatusOK, "default/login.html", gin.H{
		"msg":      "登录页",
		"username": username,
	})
}
func (con DefaultController) Reg(c *gin.Context) {
	username := con.getName(c)
	c.HTML(http.StatusOK, "default/reg.html", gin.H{
		"msg":      "注册页",
		"username": username,
	})
}

func (con DefaultController) Search(c *gin.Context) {
	keyword := c.DefaultQuery("key", "")
	page := c.DefaultQuery("page", "1")
	if keyword == "" {
		con.error(c, "请输入关键词")
		return
	}
	pageNumberInt, err := strconv.Atoi(page)
	limitInt := 10
	if err != nil || limitInt < 0 {
		pageNumberInt = 1
	}

	start := (pageNumberInt - 1) * limitInt
	sql := "select id,title,clicks,cat,cat1,cat2,top,hot,post_time ,(select cname from fa_cat where id = cat) as catname,(select cname from fa_cat where id = cat1) as cat1name,(select cname from fa_cat where id = cat2) as cat2name from fa_article where title like '%" + keyword + "%' order by id desc limit " + strconv.Itoa(start) + "," + strconv.Itoa(limitInt)
	lists := models.Selects(sql)

	sql_count := "select count(*) as count from fa_article where title like '%" + keyword + "%'"
	count := models.Selects(sql_count)

	count_articles, err := strconv.Atoi(count[0]["count"])
	pages := int(count_articles/limitInt) + 1

	page_number, err := strconv.Atoi(page)
	// 下一页
	next := page_number + 1
	if next == pages {
		next = pages
	}
	//上一页
	pre := page_number - 1
	if pre == 0 {
		pre = 1
	}

	username := con.getName(c)
	c.HTML(http.StatusOK, "default/article_list.html", gin.H{
		"msg":      "搜索页",
		"username": username,
		"lists":    lists,
		"page":     page_number, //当前第几页
		"pages":    pages,       //总页数
		"pre":      pre,
		"next":     next,
	})
}
func (con DefaultController) Cat(c *gin.Context) {
	id := c.Param("id")
	page := c.Param("page")
	limitInt := 10
	if page == "" {
		page = "1"
	}
	pageNumberInt, err := strconv.Atoi(page)
	if err != nil || limitInt < 0 {
		pageNumberInt = 1
	}
	start := (pageNumberInt - 1) * limitInt
	sql := "select id,title,clicks,cat,cat1,cat2,top,hot,post_time ,(select cname from fa_cat where id = cat) as catname,(select cname from fa_cat where id = cat1) as cat1name,(select cname from fa_cat where id = cat2) as cat2name from fa_article where cat = " + id + " order by id desc limit " + strconv.Itoa(start) + "," + strconv.Itoa(limitInt)
	lists := models.Selects(sql)

	sql_count := "select count(*) as count from fa_article where cat = " + id
	count := models.Selects(sql_count)

	count_articles, err := strconv.Atoi(count[0]["count"])
	pages := int(count_articles/limitInt) + 1

	page_number, err := strconv.Atoi(page)
	// 下一页
	next := page_number + 1
	if next == pages {
		next = pages
	}
	//上一页
	pre := page_number - 1
	if pre == 0 {
		pre = 1
	}

	username := con.getName(c)
	c.HTML(http.StatusOK, "default/article_list.html", gin.H{
		"msg":      "列表页",
		"username": username,
		"lists":    lists,
		"cid":      id,
		"page":     page_number, //当前第几页
		"pages":    pages,       //总页数
		"pre":      pre,
		"next":     next,
	})
}

func (con DefaultController) Content(c *gin.Context) {
	id := c.Param("id")
	sql := "select * from fa_article where id = " + id
	article := models.Selects(sql)
	if article[0]["title"] == "" {
		con.error(c, "参数错误")
		return
	}
	models.Db.Exec("update fa_article set clicks = clicks + 1 where id = ?", id)

	where := " id > 0"
	if article[0]["cat1"] != "0" {
		where = " cat = " + article[0]["cat1"] + " or cat1 = " + article[0]["cat1"] + " or cat2 = " + article[0]["cat1"]
	}
	sql1 := "select id,title,post_time from fa_article where " + where + " order by id desc limit 0,5"
	list1 := models.Selects(sql1)

	sql2 := "select id,title,post_time from fa_article where " + where + " order by id desc limit 5,10"
	list2 := models.Selects(sql2)

	cats := models.Selects("SELECT *  FROM fa_cat")

	article[0]["content"] = strings.Replace(article[0]["content"], "[pre]", "<pre>", -1)
	article[0]["content"] = strings.Replace(article[0]["content"], "[/pre]", "</pre>", -1)
	username := con.getName(c)
	content := article[0]["content"]
	c.HTML(http.StatusOK, "default/article_content.html", gin.H{
		"msg":      "发布页",
		"username": username,
		"article":  article[0],
		"list1":    list1,
		"list2":    list2,
		"cats":     cats,
		"content":  template.HTML(content),
	})
}

func (con DefaultController) DoLogin(c *gin.Context) {
	email := strings.TrimSpace(c.PostForm("email"))
	password_text := strings.TrimSpace(c.PostForm("pass"))

	if email == "" || password_text == "" {
		c.JSON(200, gin.H{
			"msg": "邮箱，密码不能为空",
		})
		return
	}

	rows, err := models.Db.Query("SELECT name,password,randkey  FROM fa_user where email = ?", email)
	if err != nil {
		con.error(c, err.Error())
		return
	}
	defer rows.Close()
	var name1, password1, randkey1 string
	rows.Next()
	rows.Scan(&name1, &password1, &randkey1)

	if password1 == "" {
		c.JSON(200, gin.H{
			"msg": "邮箱不存在",
		})
		return
	}

	data := []byte(password_text + randkey1)
	has := md5.Sum(data)
	password := fmt.Sprintf("%x", has) //将[]byte转成16进制

	if password != password1 {
		c.JSON(200, gin.H{
			"msg": "密码错误",
		})
		return
	}

	//初始化 session 对象
	session := sessions.Default(c)
	//设置过期时间
	session.Options(sessions.Options{
		MaxAge: 3600 * 1, // 6hrs
	})
	//设置 Session
	session.Set("username", name1)
	session.Save()

	c.JSON(200, gin.H{
		"msg":    "登录成功",
		"status": 0,
		"action": "/",
	})
}
func (con DefaultController) DoReg(c *gin.Context) {
	email := strings.TrimSpace(c.PostForm("email"))
	name := strings.TrimSpace(c.PostForm("username"))
	password_text := strings.TrimSpace(c.PostForm("pass"))

	if email == "" || name == "" || password_text == "" {
		c.JSON(200, gin.H{
			"msg": "邮箱，用户名，密码都不能为空",
		})
		return
	}

	rows, err := models.Db.Query("SELECT name, email FROM fa_user where email = ?", email)
	if err != nil {
		con.error(c, err.Error())
		return
	}
	defer rows.Close()
	var name1, email1 string
	rows.Next()
	rows.Scan(&name1, &email1)

	if name1 != "" {
		c.JSON(200, gin.H{
			"msg": "邮箱已经存在",
		})
		return
	}
	randkey := models.GetRandomString(6)
	data := []byte(password_text + randkey)
	has := md5.Sum(data)
	password := fmt.Sprintf("%x", has) //将[]byte转成16进制

	regtime := models.GetDate()

	r, err := models.Db.Exec("insert into fa_user(name, password, email,regtime,randkey,status)values(?, ?, ?,?,?,0)", name, password, email, regtime, randkey)
	if err != nil {
		con.error(c, err.Error())
		return
	}
	id, err := r.LastInsertId()
	if err != nil {
		con.error(c, err.Error())
		return
	}
	c.JSON(200, gin.H{
		"msg":    "注册成功:" + strconv.FormatInt(id, 10),
		"status": 0,
		"action": "/login",
	})

}

func (con DefaultController) News(c *gin.Context) {
	c.String(200, "News")
}

func (con DefaultController) Lov(c *gin.Context) {
	c.String(200, "Lov")
}
